//
//  LYTestViewController.m
//  artist
//
//  Created by Jay_Apple on 16/5/19.
//  Copyright © 2016年 viviyoo. All rights reserved.
//

#import "LYTestViewController.h"
#import "LYVideoModel.h"
#import "LYTestCell.h"
#import "LYCountTestModel.h"
#import "LYWebViewController.h"

@interface LYTestViewController ()
@property (weak, nonatomic) IBOutlet UILabel *testTitle;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *models;
@property (strong, nonatomic) LYTestQuestListModel *currentTest;
@property (assign, nonatomic) NSInteger page;
@property (weak, nonatomic) IBOutlet UILabel *currentPage;
@property (assign, nonatomic) NSInteger grade;
@property (weak, nonatomic) IBOutlet UILabel *gradeLabel;

@property (strong, nonatomic) NSMutableArray *testAnswers;
@property (assign, nonatomic) NSInteger right_num;

@property (copy, nonatomic) NSString *ID;

@end

@implementation LYTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"测试";
    [self getTestData];
}
#pragma mark - 懒加载
- (NSMutableArray *)testAnswers{
    
    if (_testAnswers == nil) {
        _testAnswers = [NSMutableArray array];
    }
    return _testAnswers;
    
}

#pragma mark - 构造方法
+ (instancetype)testVCWithTestID:(NSString *)ID{
    
    
    LYTestViewController *testVC = [[LYTestViewController alloc] init];
    
    testVC.ID = ID;
    
    return testVC;
    
}

#pragma mark - 重写
- (void)setModels:(NSArray *)models{
    
    _models = models;
    
    self.currentTest = [_models firstObject];
    self.page = 0;
    self.grade = 0;
}

- (void)setCurrentTest:(LYTestQuestListModel *)currentTest{
    
    _currentTest = currentTest;
    
    [self reloadData];
    
}

- (void)setPage:(NSInteger)page{
    
    _page = page;
    self.currentPage.text = [NSString stringWithFormat:@"%zd/%zd",_page + 1,self.models.count];
    
}

- (void)setGrade:(NSInteger)grade{
    
    _grade = grade;
    
    self.gradeLabel.text = [NSString stringWithFormat:@"得分：%zd",_grade];
}

#pragma mark - 网络请求


- (void)getTestData{
    
    [MBProgressHUD showMessage:nil];
    [LYRequestTool onlineTestWithQuestId:self.ID success:^(NSArray<LYTestQuestListModel *> *models) {
        [MBProgressHUD hideHUD];
        self.models = models;
        
    } failure:^(NSString *code, NSString *message) {
        [MBProgressHUD hideHUD];
    }];
    
    
}

- (void)countTestResult{
    
    LYCountTestModel *model = [[LYCountTestModel alloc] init];
    
    model.token = LYToken;
    model.ID = self.ID;
    model.answers = [self.testAnswers copy];
    model.right_num = self.right_num;
    model.error_num = self.models.count - self.right_num;
    model.score = self.grade;
    
    [LYRequestTool countTestWithcountTestModel:model success:^{
        
        
        
    } failure:^(NSString *code, NSString *message) {
       
        [MBProgressHUD showOnlyText:message];
        
    }];
    
}

#pragma mark - 刷新题目
- (void)reloadData{
    
    self.testTitle.text = self.currentTest.title;
    [self.tableView reloadData];
}


#pragma mark - tableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (self.currentTest.done) {
        return;
    }else{
        
        //判断正确
        LYOptionsModel *model = self.currentTest.options[indexPath.row];
        //正确
        if ([model.label isEqualToString:self.currentTest.answer]) {
            model.result = testResultCorrect;
            self.grade += self.currentTest.score;
            self.right_num++;
        }else{//错误
            
            model.result = testResultWrong;
            
            for (LYOptionsModel *model in self.currentTest.options) {
                if ([model.label isEqualToString:self.currentTest.answer]) {
                    model.result = testResultCorrect;
                }
            }
            
        }
        //统计答案
        [self.testAnswers addObject:model.label];
        
        self.currentTest.done = YES;
        [self.tableView reloadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSInteger page = self.page+1;
            
            if (page == self.models.count) {
                WS(weakSelf);
                
                //答题完毕
                //统计错题
                [self countTestResult];
                
                //弹框
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"答题结果" message:[NSString stringWithFormat:@"测试最终得分：%zd分",self.grade] preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }];
                
                UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"查看题解" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    UINavigationController *nav = weakSelf.navigationController;
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        LYWebViewController *webVC = [LYWebViewController webVCWithID:self.ID andType:WebTypeTestExplain];
                        
                        [nav pushViewController:webVC animated:YES];
                        
                    });
                    
                    [weakSelf.navigationController popViewControllerAnimated:NO];
                    
                }];
                
                [alert addAction:action];
                [alert addAction:action2];
                [self presentViewController:alert animated:YES completion:nil];
                
                
            }else{
                self.page++;
                //下一题
                self.currentTest = self.models[self.page];
                
            }
            
            
        });
    }
    
}


#pragma mark - tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.currentTest.options.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LYOptionsModel *model = self.currentTest.options[indexPath.row];
    
    LYTestCell * cell = [[LYTestCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    
    cell.model = model;
    
    return cell;
    
}



@end
